package com.freemarker.test.util;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreeMarkerTemplateUtils {

	private final static String Template_Dir = "templates";
    private final static Configuration config = new Configuration();

    static{
        URL url = FreeMarkerTemplateUtils.class.getClassLoader().getResource(Template_Dir);
        File dir  = new File(url.getFile());
        try {
            config.setDirectoryForTemplateLoading(dir);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        config.setObjectWrapper(new DefaultObjectWrapper());
        config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);

    }
    
    public static Template getTemplate(String templateName){
        try {
            return config.getTemplate(templateName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    
    public static String process(Template template,Object model){
        try {
           
        	StringWriter result = new StringWriter();
    		template.process(model, result);
    		return result.toString();
        	
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    public static String process(String templateName,Object model){
        return process(getTemplate(templateName),model);
    }
    

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("id", "live");
        map.put("sign", "adbc1234");
        map.put("userID", "lamfire");
        map.put("departureDateTime", "1010-8-8");
        map.put("originLocation", "CAN");
        map.put("destinationLocation", "PEK");
        map.put("airlineCode", "AC");
        
        String content = FreeMarkerTemplateUtils.process("FlightQueryRequest.ftl", map);
        System.out.println(content);
    }

}
